<template>
  <div class="common-page page-stats-order-city" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <!-- <comp-paths class="route" :paths="['/stats', $route.fullPath]"></comp-paths> -->
      <div class="title">
        <div class="text">{{ $options.title }}</div>
        <el-date-picker type="date" v-model="filters.startTime" size="small" style="margin-right: 12px; width: 200px"
                        format="起始yyyy年M月d日" value-format="timestamp" placeholder="起始日期" :readonly="loading"
                        @change="search()"></el-date-picker>
        <el-date-picker type="date" v-model="filters.endTime" size="small" style="margin-right: 12px; width: 200px"
                        format="截止yyyy年M月d日" value-format="timestamp" placeholder="截止日期" :readonly="loading"
                        @change="search()"></el-date-picker>
        <el-select size="small" v-model="filters.userRole" clearable placeholder="角色" @change="search">
          <el-option v-for="role in userRoleArr" :key="role.value" :value="role.value" :label="role.label"></el-option>
        </el-select>

        <el-select size="small" v-model="filters.activityType" clearable placeholder="终端" @change="search">
          <el-option v-for="role in activityTypeArr" :key="role.value" :value="role.value" :label="role.label"></el-option>
        </el-select>

        <el-button type="plain" size="small" icon="el-icon-top" @click="setCity()" v-if="cityId">返回</el-button>
      </div>
    </div>
    <div class="common-page__body page-stats-order-city__body" v-if="!open">
      <div class="row">
        <div class="col col--2em">序号</div>
        <div class="col">
          <span v-if="cityId">县区</span>
          <span v-else>城市</span>
        </div>
        <div class="col col--4em">活跃度</div>
      </div>
      <div class="row" v-for="(city, index) in cityList" :key="city.id">
        <div class="col col--2em">
          <span>{{ index + 1 }}</span>
        </div>
        <div class="col" v-if="cityId"  style="cursor: pointer; color:#146CFF; ">{{
            city.name
          }}
        </div>
        <div class="col col--click" @click="setCity(city)" v-else>
          <span class="key">{{ city.name }}</span>
        </div>
        <div class="col col--4em">{{ city.count }}</div>

      </div>
      <div class="row" v-if="cityCountAll.count > 0">
        <div class="col col--2em">
          <span>{{ '-' }}</span>
        </div>
        <div class="col col--click" >
          <span class="key">{{ '合计' }}</span>
        </div>
        <div class="col col--4em">{{ cityCountAll.count }}</div>
      </div>
    </div>
    <div class="pagecoun" v-if="open">
      <div class="TableList" v-loading.fullscreen="loading">
        <el-table border :data="countryList" style="width: 100%" :header-cell-style="{
                        background:'#F6F6F6',color:'#000000'}"
        >
          <el-table-column type="index" label="序号" width="60"/>
          <!-- <el-table-column prop="id" label="id" v-if="openId" width="auto" min-width="120" /> -->
          <el-table-column prop="corpName" label="企业/项目信息" width="auto" min-width="160"/>
          <el-table-column prop="title" label="事项标题" width="auto" min-width="160"/>
          <el-table-column prop="tagName" label="事项分类" width="auto" min-width="120"/>
          <el-table-column prop="fwzy" label="服务专员" width="auto" min-width="120"/>
          <el-table-column prop="level" label="事项层面" width="auto" min-width="60"/>
          <el-table-column prop="status" label="事项状态" width="auto" min-width="60"/>
          <el-table-column prop="evaluationFlag" label="评价状态" width="auto" min-width="60"/>
          <el-table-column prop="userName" label="提交人" width="auto" min-width="120"/>
          <el-table-column prop="createdAt" label="提交时间" width="auto" min-width="120"/>
        </el-table>
        <div class="paginationd">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10,20,30]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import mixin from "../mixin";
import {string, int} from "../util";

export default {
  name: "page-stats-liveness-city",
  title: "用户活跃度",
  nodes: ["/menu/stats"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    cityId: "",
    filters:{
      startTime: null,
      endTime: null,
      userRole: null,
      activityType: null
    },
    cityList: [],
    cityCountAll:{
      label:"",
      count:0
    },
    open: false,
    countryList: [],
    pageNum: 1,
    pagesize: 10,
    total: 0,
    areaId: null,
    status: null,
    userRoleArr:[
      {label:'全部',value:null},
      {label:'服务专员',value:'100'},
      {label:'企业人员',value:'200'},
      {label:'政府专员',value:'300'},
    ],
    activityTypeArr:[
      {label:'全部',value:null},
      {label:'网页',value:0},
      {label:'小程序',value:1},
      {label:'APP',value:2}
    ],
    managerQuNums:managerQuNums
  }),
  methods: {
    handleSizeChange(val) {
      this.countryList = [];
      this.total = 0
      let a
      if (this.status == 5) {
        this.pagesize = val;
        a = {
          areaId: this.areaId,
          pageNum: this.pageNum,
          pageSize: val,
          status: this.status
        }
      } else {
        this.pagesize = val;
        a = {
          areaId: this.areaId,
          pageNum: this.pageNum,
          pageSize: val
        }

      }
      this.getsetxian(a)

    },
    handleCurrentChange(val) {

      this.total = 0
      this.countryList = [];
      // this.pageNum = val;
      let a = {
        areaId: this.areaId,
        pageNum: val,
        pageSize: this.pagesize
      }
      this.getsetxian(a)


    },
    formatDate(value) {
      let date = new Date(value);//这个是纳秒的，想要毫秒的可以不用除以1000000
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? ('0' + MM) : MM;
      let d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      let h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      let m = date.getMinutes();
      m = m < 10 ? ('0' + m) : m;
      let s = date.getSeconds();
      s = s < 10 ? ('0' + s) : s;
      return y + '年' + MM + '月' + d + '日 ' + h + ':' + m + ':' + s;
    },
    getsetxian(a) {
      this.plugins.user.getcountryList(a).then((res) => {
        this.total = res.data.numberOfElements;
        this.pageNum = a.pageNum

        res.data.list.forEach(element => {
          var str = '';
          element.workTagMappWorkTagMapList.forEach(item => {
            str += item.tagName + ","
          })
          let str1 = '';
          if (element.level) {
            if (element.level == "1") {
              str1 = "县级"
            }
            if (element.level == "2") {
              str1 = "市级"
            }
            if (element.level == "3") {
              str1 = "自治区级"
            }
          } else if (element.level === "") {
            if (element.deptIdDepartment.areaId) {
              str1 = "县级"
            } else if (element.deptIdDepartment.areaId == undefined) {
              str1 = "市级"

            } else if (element.deptIdDepartment.cityId == undefined) {
              str1 = "自治区级"

            }
          }
          let status = ''
          if (element.status == 1) {
            status = '待提交'
          } else if (element.status == 2) {
            status = '已提交'
          } else if (element.status == 3) {
            status = '已退回'
          } else if (element.status == 4) {
            status = ''
          } else if (element.status == 5) {
            status = '已办结'
          }
          let evaluationFlag = ""
          if (element.evaluationFlag == 1 && element.status == 5) {
            evaluationFlag = '待评价'
          } else if (element.evaluationFlag == 1) {
            evaluationFlag = '-'
          } else if (element.evaluationFlag == 2) {
            evaluationFlag = '已评价'

          }
          let userName = element.userIdUserAccount.userName + '/' + element.userIdUserAccount.userAccount;
          let createdAt = this.formatDate(Number(element.createdTime));
          let corptype = ''
          if (element.corpIdCorpDetail.corpType == "1") {
            corptype = "企业"
          } else if (element.corpIdCorpDetail.corpType == "2") {
            corptype = "项目"

          } else if (element.corpIdCorpDetail.corpType == "3") {
            corptype = "园区"

          }
          let corpName = element.corpIdCorpDetail.corpName + ' /' + corptype
          let obj = {
            corpName: corpName,
            title: element.title,
            tagName: str.slice(0, str.length - 1),
            fwzy: "",
            level: str1,
            completeContent: element.completeContent,
            status: status,
            evaluationFlag: evaluationFlag,
            userName: userName,
            createdAt: createdAt
          }

          this.countryList.push(obj)
        });

      })
    },
    setban(params, b) {
      this.status = b
      this.areaId = params
      let a = {
        areaId: params,
        pageNum: this.pageNum,
        pageSize: this.pagesize,
        status: this.status
      }
      this.open = true;
      this.getsetxian(a)
    },
    setxian(params) {
      this.areaId = params;
      let a = {
        areaId: params,
        pageNum: this.pageNum,
        pageSize: this.pagesize
      }
      this.open = true;
      this.getsetxian(a)
    },
    setCity(city) {
      this.countryList = [];
      this.pageNum = 1;
      this.open = false;
      if (this.loading) return;
      this.cityId = city ? city.id : "";
      this.search(true);
    },
    search(clean) {
      if (this.loading) return;
      if (clean) this.cityList = [];
      let cityId = this.cityId;
      let startTime = this.filters.startTime;
      if(startTime){
        startTime = new Date(startTime)
        startTime.setHours(0,0,0)
        startTime = startTime.getTime()
      }
      let endTime = this.filters.endTime;
      if(endTime){
        endTime = new Date(endTime)
        endTime.setHours(23,59,59)
        endTime = endTime.getTime()
      }
      this.loading = true;
      this.plugins.user.getStatsLiveCity({cityId, ...this.filters}).then((res) => {

        this.loading = false;
        if (res.code === 0) {
          this.cityList = res.data.map((data) => ({
            ...data,
            id: string(data.areaId),
            name: string(data.name),
            stats: {
              ordersTotal: int(data.countAll),
              ordersFinishedTotal: int(data.countStatus_5),
              ordersFinishedPercent: int(int(data.countStatus_5) / int(data.countAll), 4) / 100,
            },
          })).sort((a, b) => {
            let a1 = a.stats.ordersFinishedPercent;
            let a2 = a.stats.ordersFinishedTotal;
            let a3 = a.stats.ordersTotal;
            let a4 = a.id;
            let b1 = b.stats.ordersFinishedPercent;
            let b2 = b.stats.ordersFinishedTotal;
            let b3 = b.stats.ordersTotal;
            let b4 = b.id;
            return a1 === b1 ? a2 === b2 ? a3 === b3 ? a4 - b4 : b3 - a3 : b2 - a2 : b1 - a1;
          });
          // 没有选城市之前
          if(!this.cityId){
            if(this.profile.isAdmin == 0 && !this.managerQuNums.includes(this.profile.number)){
              this.cityList = []
            }
            if(!this.managerQuNums.includes(this.profile.number)){
              const cityIds = this.profile.depments.map(x=>x.dept?.city?.id).filter(x=>x != null)
              this.cityList = this.cityList.filter(x=>cityIds.includes(x.id))
            }
          }

        } else {
          this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
        }

        this.cityCountAll.count = this.cityList.map(x=>x.count).reduce((a,b)=>a+b,0)

      });
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      this.loading = true;
      this.$root.$refs.navbar.init();
      this.plugins.user.call(async () => {
        let res = await this.plugins.user.init();
        if (res.code === 0) {
        }
        return res;
      }, async () => {
        if (this.access(this.$route.name)) return {code: 0};
        return this.env.xhrErrors.find((error) => error.code === 4);
      }).then((res) => {
        this.loading = false;
        this.$root.$refs.navbar.init();
        if (res.code === 0) {
          this.search();
        } else if (res.code === 2) {
          this.$root.$refs.navbar.login();
        } else {
          this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
        }
      });
    },
  },
};
</script>

<style lang="scss">
.page-stats-order-city {
  overflow: hidden;
  padding-bottom: 0px;
}

.page-stats-order-city__body {
  display: flex;
  flex-direction: column;

  & > .row {
    flex: 0 0 auto;
    display: flex;
    width: 640px;

    & > .col {
      flex: 1 1 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 0 2px 2px 0;
      padding: 8px 9px;
      color: #333;
      font-size: 14px;
      line-height: 16px;
      text-align: center;
      background-color: #f6f6f6;

      & > .key {
        color: #1677ff;
      }
    }

    & > .col--click {
      cursor: pointer;
    }

    & > .col--2em {
      flex: 0 0 auto;
      width: 2em;
    }

    & > .col--3em {
      flex: 0 0 auto;
      width: 3em;
    }

    & > .col--4em {
      flex: 0 0 auto;
      width: 4em;
    }

    &:first-child {
      & > .col {
        font-weight: bold;
      }
    }
  }
}

.pagecoun {
  width: 100%;
  height: 100%;

  .TableList {
    width: 100%;
    height: 100%;
    overflow: auto;
    padding-bottom: 5rem;
    margin-bottom: 5rem;

    .paginationd {
      height: 6rem;
    }
  }
}
</style>
